from __future__ import absolute_import
import logging
import os.path
import forest
from os.path import join #, exists
from forest.api import Command, get_tool

logger = logging.getLogger('forest.commands.EmbedInstaller')

forest_dir = os.path.dirname(os.path.abspath(forest.__file__))

DEFAULT_PTH= '''import sys; sys.__plen = len(sys.path)
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys, '__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)
'''
class EmbedInstaller(Command):
    ''' Copies forest and dependencies to the install root.
    '''
    __register__ = 'commands.forest.EmbedInstaller'

    # TODO: refactor into
    def get_iso_root(self):
        return os.path.join(self._config.get_build_root(), 'isoroot')

    def join_iso_root(self, *args):
        return os.path.join(self._config.get_build_root(), 'isoroot', *args)

    def run(self, config):
        self._config = config
        installtree = config.get_install_root()

        #TODO: fix these paths
        get_tool('system.mkdir')(self.join_iso_root('isolinux'))

        src = config.get('forest.source', False)

        if not src:
            return

        Command.SIGNAL_COMMAND_PROGRESS(self, message='Installing forest from %s' % forest_dir)

        # TODO: locate python packages dir
        #installto = os.environ['PYTHONPATH'] = join(installtree, 'usr', 'lib', 'python2.7', 'site-packages')

        # clean up after distutils
        get_tool('system.remove')('forest.egg-info')

        with get_tool('system.cd')(installtree):
            get_tool('system.ln')('/bin/systemd', 'init')

        #TODO: fix these paths. MOVE THIS OUT INTO LIVE BUILDING
        splash_path = config.get_defined_file('splash.png')
        get_tool('system.copy')(splash_path, self.join_iso_root('isolinux', 'splash.png'))

        # Copy forest whereever it is
        get_tool('system.copy')(join(forest_dir,'bin', 'install.py'), join(installtree, 'usr', 'bin'))

        # TODO: this will need a fix if egg'd
        get_tool('system.copytree')(join(forest_dir), join(installtree, 'usr', 'lib', 'python2.7', 'site-packages'))

        get_tool('files.write')(join(installtree, 'usr', 'lib', 'python2.7', 'site-packages','easy_install.pth'), DEFAULT_PTH)


        #get_tool('system.execute')(['chmod', '+x', join(installtree, 'usr', 'bin', 'tree-build')])


        #get_tool('system.copy')(join(forest_dir,'bin', 'tree-build'), join(installtree, 'usr',' bin'))

        #get_tool('files.write')(join(installtree, 'usr', 'lib', 'python2.7', 'site-packages','easy_install.pth'),DEFAULT_PTH)


